<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="部门id" prop="deptId">
            <el-input v-model="pd.queryParams.deptId" placeholder="请输入部门id" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="用户id" prop="userId">
            <el-input v-model="pd.queryParams.userId" placeholder="请输入用户id" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['demo:demo2:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()"
                       v-hasPermi="['demo:demo2:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()"
                       v-hasPermi="['demo:demo2:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo2:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.demo2List" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="主键" align="center" prop="id" v-if="true"/>
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['hrp:example:edit']">
              {{ scope.row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="部门id" align="center" prop="deptId"/>
        <el-table-column label="用户id" align="center" prop="userId"/>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dictTag :options="sys_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="值" align="center" prop="remark"/>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['demo:demo2:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                         v-hasPermi="['demo:demo2:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <Pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="1000px" append-to-body>
      <el-form ref="demo2FormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门id" prop="deptId">
              <el-input v-model="pd.form.deptId" placeholder="请输入部门id"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="pd.form.userId" placeholder="请输入用户id"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="pd.form.status" placeholder="请选择状态">
                <el-option v-for="dict in sys_status" :key="dict.value"
                           :label="dict.name" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="值" prop="remark">
              <el-input v-model="pd.form.remark" placeholder="请输入值"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button v-if="!pd.form.id" icon="Plus" type="success" @click="submitForm">保存单据</el-button>
          <el-button v-if="pd.form.id" icon="Delete" type="danger" @click="handleDelete(pd.form.id)">删除单据
          </el-button>
        </el-col>
        <el-col v-if="pd.form.id" :span="1.5">
          <el-button icon="Plus" type="success" @click="submitForm">修改单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="pd.dialog.visible = false">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="lineAddOpen" v-hasPermi="['hrp:example:add']">新增一行
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Refresh" @click="getLineList">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="pd.loading" :data="pd.form.line">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="父键" width="180" align="center" prop="id"/>
        <el-table-column label="主键" width="180" align="center" prop="lineId"/>
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-input v-model="scope.row.name" placeholder="名称"/>
          </template>
        </el-table-column>
        <el-table-column label="编码" align="center" prop="code">
          <template #default="scope">
            <el-input v-model="scope.row.code" placeholder="编码"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['hrp:example:del']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList"/>
    </el-dialog>
  </div>
</template>

<script setup name="Example2" lang="ts">
import {addExample2, delExample2, delExample2Line, listExample2, listExample2Line, updateExample2,
  example2VO, example2LineVO} from '@/views/demo/example2/api';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {sys_status} = toRefs<any>(proxy?.useDict('sys_status'));

const queryFormRef = ref<ElFormInstance>();
const demo2FormRef = ref<ElFormInstance>();

const pd = reactive({
  demo2List: <example2VO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <example2VO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  lineTotal: 0,
  form: <example2VO>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  queryParams: <example2VO>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    deptId: undefined,
    userId: undefined,
    id: undefined,
    deptName: undefined,
    status: undefined,
    params: {}
  },
  queryLineParams: <example2LineVO>{
    pageNum: 1,
    pageSize: 10,
    id: undefined
  },
  rules: <ElFormRules>{
    id: [{required: true, message: "主键不能为空", trigger: "blur"}],
    name: [{required: true, message: "名称不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}],
  }
});

/** 查询测试主从列表 */
async function getList() {
  pd.loading = true;
  const res = await listExample2(pd.queryParams);
  pd.demo2List = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 查询测试子列表 */
function getLineList() {
  pd.loading = true;
  pd.queryLineParams.id = pd.form.id;
  listExample2Line(pd.queryLineParams).then(res => {
    pd.form.line = res.rows;
    pd.lineTotal = res.total;
    pd.loading = false;
  });
}


/** 表单重置 */
const reset = () => {
  pd.form = {
    id: undefined,
    name: undefined,
    deptId: undefined,
    userId: undefined,
    status: undefined,
    remark: undefined,
    line: []
  };
  demo2FormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: example2VO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.title = "新增测试主从";
  pd.dialog.visible = true;
}

/** 新增一行按钮操作 */
async function lineAddOpen() {
  let line: example2LineVO = {
    lineId: undefined,
    name: '',
    code: ''
  };
  pd.form.line.push(line)
}

/** 修改按钮操作 */
async function handleUpdate(row?: example2VO) {
  const data = row || pd.selectVO[0];
  Object.assign(pd.form, data);
  getLineList();
  pd.dialog.visible = true;
  pd.dialog.title = "修改测试主从";
}

/** 提交按钮 */
function submitForm() {
  demo2FormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (pd.form.id) {
        pd.buttonLoading = true;
        await updateExample2(pd.form).finally(() => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess("修改成功");
        });
      } else {
        await addExample2(pd.form).finally(() => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess("新增成功");
        });
      }
      pd.dialog.visible = false;
      await getList();
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(id?: string | number) {
  const _ids = id ? id : pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除测试主从编号为"' + _ids + '"的数据及子数据？').finally(() => pd.loading = false);
  await delExample2(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  pd.dialog.visible = false;
  await getList();
}

/** 删除子表操作 */
async function delLine(row: example2LineVO) {
  if (row.lineId === undefined) {
    const index = pd.form.line.indexOf(row);
    pd.form.line.splice(index, 1);
    return;
  }
  proxy?.$modal.confirm('是否确认删除 子单号为:"' + row.lineId + '"的数据项？').then(function () {
    return delExample2Line(row.lineId);
  }).then(() => {
    const index = pd.form.line  .indexOf(row);
    pd.form.line.splice(index, 1);
    proxy.$modal.msgSuccess("删除成功");
    // getLineList();
  }).catch(() => {
  });

}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('demo/demo2/export', {
    ...pd.queryParams
  }, `demo2_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
